<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
	<title>AeroSense Care</title>
	<link rel="stylesheet" href="./css/echome.css">
	<script type="text/javascript" src="./js/flexible.js"></script>
	<script type="text/javascript" src="./js/jquery-v2.1.4.min.js"></script>
	<script type="text/javascript" src="./js/echarts.min.js"></script>

</head>

<body>

<section id="show_all_data">

	<div class="cd-select-item ">
		<div class="header">
			<ul class="ui-nav-home">
				<li data-nav="Sleep">
					<span class="data_lan" data-lan="SleepReport">Sleep Report<em></em></span>
				</li>
				<li  data-nav="ADL">
					<span class="data_lan" data-lan="ADLReport">ADL Report<em></em></span>
				</li>
				<a class="home_link data_lan" data-lan="more" href="javascript:;">More</a>
			</ul>
		</div>
		<div class="Tophome ">
			<div class="sleepDay hide" >
				<div class="sleepDayDiv">
					<p class="SleepScore dataTime" > 05/27 </p>
					<div class="scoreFigure" id="sleepNum">82</div>
					<p class="SleepScore data_lan" data-lan="SleepScore">Sleep Score</p>
					<ul class="star">
						<li class="emptyStar"><a href="javascript:;">1</a><a href="javascript:;">2</a></li>
						<li class="emptyStar"><a href="javascript:;">3</a><a href="javascript:;">4</a></li>
						<li class="emptyStar"><a href="javascript:;">5</a><a href="javascript:;">6</a></li>
						<li class="emptyStar"><a href="javascript:;">7</a><a href="javascript:;">8</a></li>
						<li class="emptyStar"><a href="javascript:;">9</a><a href="javascript:;">10</a></li>
					</ul>
					<div class="wrapper" >
						<div class="one item">
							<p class="data_lan" data-lan="TotalSleepTime">Total Sleep Time</p>
							<p class="SleepAnalysis c1 " id="sleepTime">8h 20min</p>
							<img src="./img/img_sleep@2x.png">
						</div>
						<div class="two item">
							<p class="data_lan" data-lan="AvgRate">Avg.respiratory rate</p>
							<p class="SleepAnalysis"><b class="c2" id="breathAvg">17</b> <span class="data_lan" data-lan="bpm">bpm</span> </p>
							<img src="./img/icon_huxida@2x.png">
						</div>
					</div>
				</div>
				<div class="no">
					<img style="height: 1.9rem" src="./img/img_loss@2x.png" alt="">
					<p class="data_lan" data-lan="Records">No Records</p>
				</div>

			</div>
			<div class="ADLDay hide " >
				<div class="ADLDayDiv">
					<p class="report_type dataTime">05/27</p>
					<img class="Top_img" src="./img/top.png">
					<div id="main1" style="width: 6rem; height:4.5rem;margin: 0 auto"></div>
					<div class="cd-select" id="chklist">
						<div class="cd-select-item cd-select-item-b active sleep_show" id="sleeplegend">
							<span class="info"><b class="data_lan" data-lan="Sleep">Sleep</b><i class="sleepTimeAllTime">2h 30min</i></span>
						</div>
						<div class="cd-select-item cd-select-item-b active bathroom_show" id="bathRoomlegend" style="display: none;">
							<span class="info"><b class="data_lan" data-lan="Bathroom">Bathroom</b><i id="bathroomTime">2h 30min</i></span>
						</div>
						<div class="cd-select-item cd-select-item-b active activity_show" id="activitylegend">
							<span class="info"><b class="data_lan" data-lan="Activity">Activity</b><i id="activityTime">4h 30min</i></span>
						</div>
						<div class="cd-select-item cd-select-item-b active sedentary_show" id="Sedentarylegend">
							<span class="info"><b class="data_lan" data-lan="Sedentary">Sedentary</b><i id="sedentaryTime">7h 30min</i></span>
						</div>
						<div class="cd-select-item cd-select-item-b active outOfRoom_show" id="outlegend">
							<span class="info"><b class="data_lan" data-lan="Outroom">Out of the room</b><i id="outOfRoomTime">1h 30min</i></span>
						</div>
					</div>
				</div>
				<div class="no">
					<img style="height: 1.9rem" src="./img/img_loss@2x.png" alt="">
					<p class="data_lan" data-lan="Records">No Records</p>
				</div>
			</div>
		</div>
	</div>
</section>

<script type="text/javascript">


	var en={
		"SleepReport":"Sleep Report",
		"ADLReport":"ADL Report",
		"more":"More",
		"Lastupdate":"Last update",
		"SleepScore":"Sleep Score",
		"TotalSleepTime":"Total Sleep Time",
		"AvgRate":"Avg.respiratory rate",
		"Sleep":"Sleep",
		"Bathroom":"Bathroom",
		"Activity":"Activity",
		"Sedentary":"Sedentary",
		"Outroom":"Out of the room",
		"Records":"Sleep report is not available.",
		"bpm":"bpm",
		"hour":"h  ",
		"min":"min"
		}
	var zh={
		"SleepReport":"睡眠报告",
		"ADLReport":"活动量报告",
		"more":"更多",
		"Lastupdate":"最近更新",
		"SleepScore":"睡眠质量",
		"TotalSleepTime":"睡眠时长",
		"AvgRate":"呼吸平均值",
		"Sleep":"睡眠时间",
		"Bathroom":"卫浴使用",
		"Activity":"活动时间",
		"Sedentary":"久坐时间",
		"Outroom":"离开房间",
		"Records":"暂无数据",
		"bpm":"次/分钟",
		"hour":"小时  ",
		"min":"秒"
		}
function minute2HHmmlan(minute,HTime,MTime) {
    if (minute === null || minute === 0 || isNaN(minute)) {
        return "0"+MTime
    }
    if (minute < 60) {
        return minute + MTime
    }
    let hour = minute / 60
    let min = minute % 60
    if (hour === 0) {
        return min + MTime
    }
    return parseInt(hour) + HTime + min + MTime
}
/**
 * 显示
 */
function showData(a) {

	if(a==0){
		$(".ADLDayDiv").css({display: "block"})
		$(".ADLDay .no").css({display: "none"})
		$(".sleepDayDiv").css({display: "block"})
		$(".sleepDay .no").css({display: "none"})
	}
	if(a==1){
		$(".sleepDayDiv").css({display: "block"})
		$(".sleepDay .no").css({display: "none"})
		$(".ADLDayDiv").css({display: "block"})
		$(".ADLDay .no").css({display: "none"})
	}
    $("html,body").scrollTop(0);
}
/**
 * 隐藏
 */
function hideData(a) {

	if(a==0){
		$(".ADLDayDiv").css({display: "none"})
		$(".ADLDay .no").css({display: "block"})
		$(".sleepDayDiv").css({display: "block"})
		$(".sleepDay .no").css({display: "none"})
	}
	if(a==1){
		$(".ADLDayDiv").css({display: "block"})
		$(".ADLDay .no").css({display: "none"})
		$(".sleepDayDiv").css({display: "none"})
		$(".sleepDay .no").css({display: "block"})
	}
    $("html,body").scrollTop(0);
}


function ShowJSON(a){
	//JSON.parse(json)
	userinfo = a;

	var baseLang = userinfo["lan"];
	var report = userinfo["report"];
	var num =  userinfo["num"];
	var USencrypt = userinfo["encrypt"];
	var url = userinfo["serverIp"]+":"+userinfo["serverPort"];
	var url2 = userinfo["ADLserverIp"]+":"+userinfo["ADLserverPort"];

	$(".data_lan").each(function(idx, ele){
			var key = $(ele).attr("data-lan");
			var val_cmd = baseLang+"."+key;
			var val = eval("("+val_cmd+")");
		    $(ele).text(val);
	});

	var nowDate = new Date();
	var year = nowDate.getFullYear();
  	var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
	var date = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
	var dt = year+""+month+""+date;
//初始化
	ShowReportDiv(0,1,num,dt,"Sleep");

	//显示设备个数
    $(".ui-nav-home").on("click","li",function(){
	  if($(this).attr("data-nav")==="ADL"){
		  $(".ui-nav-home li").eq(1).addClass("active").siblings().removeClass("active");
		  $(".sleepDay").hide();$(".ADLDay").show();
		  init(null, null,dt);
		  printLog("ADL");
	  }
	  if($(this).attr("data-nav")==="Sleep"){
		  $(".ui-nav-home li").eq(0).addClass("active").siblings().removeClass("active");
		  $(".ADLDay").hide();$(".sleepDay").show();
		  initc(null, null,dt);
		  printLog("Sleep");

	  }
    })

	function ShowReportDiv(d1,d2,num,dates,r){
		if(num === "0"){
			if(report == "Sleep"){
				 	initc(null, null,dates);
					$(".ui-nav-home li").eq(d1).show();
					$(".ui-nav-home li").eq(d1).addClass("active").siblings().removeClass("active");
					$(".Tophome > div").eq(d2).hide().siblings().show();
			}
			if(report == "ADL"){
					init(null, null,dates);
					$(".ui-nav-home li").eq(d2).show();
					$(".ui-nav-home li").eq(d2).addClass("active").siblings().removeClass("active");
					$(".Tophome > div").eq(d1).hide().siblings().show();
			}
		}
		if(num === "1"){
					$(".ui-nav-home li").show();
			if(r == "ADL"){
				 	init(null, null,dates);
					$(".ui-nav-home li").eq(d2).addClass("active").siblings().removeClass("active");
					$(".Tophome > div").eq(d1).hide().siblings().show();
			}
			if(r == "Sleep" || report == "ADL"){
					initc(null, null,dates);
					$(".ui-nav-home li").eq(d1).addClass("active").siblings().removeClass("active");
					$(".Tophome > div").eq(d2).hide().siblings().show();
			}
		}
	}
	$(".home_link").on("click",function(){
		var uiNav = $(".ui-nav-home li.active").attr("data-nav");
		console.log(uiNav)
		langLink(uiNav);
	})

	function langLink(r){
			 if(r == "ADL"){
					if(baseLang == 'en'){
						toReportMore("Ecarts");
					}else{
						toReportMore("Ecarts_zh");
					}
			}
			if(r == "Sleep"){
					if(baseLang == 'en'){
						toReportMore("Ecarts_Sleep")
					}else{
						toReportMore("Ecarts_Sleep_zh")
					}
			}
	}

    /**
     * 表盘
     * @param data
     */
    function topEcharts(data) {
        const myChart1 = echarts.init(document.getElementById('main1'));
        data.unshift({value: 0, name: '1'},
            {value: 0, name: '2'},
            {value: 0, name: '3'},
            {value: 0, name: '4'},
            {value: 0, name: '5'},
            {value: 0, name: ' '})
        let option1 = {
            color: ["#90B5FF","#FAB57A ", "#C9EB85", "#CFCFCF ", "#80D6FF", "#ffffff"],
            series: [
                {
                    // name: '访问来源',
                    type: 'pie',
                    radius: ['60%', '75%'],
                    labelLine: {
                        show: false
                    },
                    label: {
                        align: 'right',
                        show: false
                    },
                    emphasis: {
                        label: {
                            show: false
                        }
                    },
                    data: data
                }
            ]
        };
        myChart1.setOption(option1);
    }

    /**
     * 控制界面显示
     * @param data
     */
    function controllDivShow(roomType) {
        for (let i in roomType) {
            switch (roomType[i].roomType) {
                case 1:
                case 4:
                case 6:
                    //客厅,厨房,书房
                    $(".slee_show").hide();
                    $(".bathroom_show").hide();
                    break
                case 2:
                    //卧室
                    $(".bathroom_show").hide();
                    break
                case 3:
                    //卫浴
                    $(".slee_show").hide();
                    $(".sedentary_show").hide();
                    $(".activity_show").hide();
                    break
                case 7:
                    //其他
                    $(".slee_show").hide()
                    $(".sedentary_show").hide();
                    $(".activity_show").hide();
                    $(".bathroom_show").hide();
                    break
            }
        }
    }


	//日期
	var Lastupdate  = eval("("+baseLang+".Lastupdate)");
	$(".dataTime").html(Lastupdate+" : "+month+"/"+date);

	var RecordsText = eval("("+baseLang+".Records)");
  	$(".Records").text(RecordsText);



    /**
     * 渲染表盘以及下面选项
     * @param data
     */
    function renderDial(data) {
        //渲染表盘
        if (data.pic === null) {
            topEcharts([]);
        } else {
            topEcharts(data.pic);
        }
		var Lghour = eval("("+baseLang+".hour)");
		var Lgmin  = eval("("+baseLang+".min)");
        //渲染时间
        let sleepTime = minute2HHmmlan(data.sleepTime,Lghour,Lgmin);
        $(".sleepTimeAllTime").html(sleepTime);
        let bathroomTime = minute2HHmmlan(data.toiletAllTime,Lghour,Lgmin);
        $("#bathroomTime").html(bathroomTime);
        let activityTime = minute2HHmmlan(data.activeAllTime,Lghour,Lgmin);
        $("#activityTime").html(activityTime);
        let sedentaryTime = minute2HHmmlan(data.sdeAllTime,Lghour,Lgmin);
        $("#sedentaryTime").html(sedentaryTime);
        let outOfRoomTime = minute2HHmmlan(data.liveRoomAllTime,Lghour,Lgmin);
        $("#outOfRoomTime").html(outOfRoomTime);
    }

    /**
     * 星星渲染
     * @param rate
     */
    function get_rate(rate) {
        $("#sleepNum").html(rate);
        var num = parseInt(rate / 10);
        if (num === 1) {
            $(".star  li").eq(0).attr("class", "halfStar");
        }
        for (var i = 0; i <= (num / 2) - 1; i++) {
            $(".star  li").eq(i).attr('class', 'fullStar');
            //奇数
            if (num === 1 || num === 3 || num === 5 || num === 7 || num === 9) {
                $(".star  li").eq(i + 1).attr("class", "halfStar");//半星
            }
        }
    }

    /**
     * 渲染界面
     * @param data data
     */
    function renderHtml(data) {
        //是否显示
        controllDivShow(data.roomType);
        //表盘
        renderDial(data);

    }

    /**
     * 请求，如果参数不对或者失败的话就500ms重试
     * @param dayStr
     * @param year
     * @param allTime
     */
    function init(dayStr, year, allTime) {

		//renderHtml();
        const renderInterval = setInterval(() => {
            const encrypt = USencrypt
            if (encrypt != null) {
//                ajax请求
                $.ajax({
					url: url2+"/healthReport/showDay",
                    contentType: "application/json",
                    data: JSON.stringify({encrypt, dayStr, year, allTime}),
                    type: "post",
                    success: function (ret) {
                        if (ret.code === 100 ) {
                            //成功
                            showData(0);
							renderHtml(ret.data);
                        } else {
                            //失败
                            hideData(0);
                        }
                    },
                    error: function (error) {
						hideData(0);
                    }
                })
                clearInterval(renderInterval);
            }
        }, 500);
    }

    /**
     * 渲染分数以及其它数据
     * @param data
     */
    function renderNav(data) {
        //分数
        get_rate(data.sleepCore);
		var Lghour = eval("("+baseLang+".hour)");
		var Lgmin  = eval("("+baseLang+".min)");
        $("#sleepTime").html(minute2HHmmlan(data.sleepTime,Lghour,Lgmin));
        $("#breathAvg").html(data.breathAvg ? data.breathAvg : 0);
        $("#heartAvg").html(data.heartAvg ? data.heartAvg : 0);
    }
    /**
     * 渲染界面
     * @param data
     */
    function renderHtmlc(data) {

		renderNav(data);
    }
    /**
     * 请求
     * @param dayStr
     * @param year
     * @param allTime
     */
    function initc(dayStr, year, allTime) {

        const renderInterval = setInterval(() => {
            const encrypt = USencrypt
            if (encrypt != null) {
                //ajax请求
                $.ajax({
					url: url+"/sleepReport/showDay",
                    contentType: "application/json",
                    data: JSON.stringify({encrypt, dayStr, year, allTime}),
                    type: "post",
                    success: function (ret) {
                        if (ret.code === 100) {
                            showData(1)
							renderHtmlc(ret.data);
                        } else {
                            hideData(1)
                        }
                    },
                    error: function (error) {

                    }
                })
                clearInterval(renderInterval);
            }
        }, 500);
    }
}
	var u = navigator.userAgent;
	var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
    /**
     * 调用ios
     */
    function IosTopHome() {
        //通知ios发送需要的数据
        window.webkit.messageHandlers.regcallBack.postMessage("homeReport");
    }
    /**
     * 由ios主动调用
     * @param encrypt
     */
	var userinfo;
    function retEncryptHome(json) {
//		json = {"ADLserverIp": "https:\/\/aerosense.ax-end.com", "ADLserverPort": "9903", "lan": "en","num": "1", "serverPort": "9903", "serverIp": "https:\/\/aerosense.ax-end.com","report" : "ADL","encrypt" : "13360111504B57313534054150"};
		ShowJSON(json);
    }


    /**
     * 获取属性
     */
    function getEncryptHome() {
        if(isAndroid) {
            regcallBack.ready();
        } else {
            //通知ios
            IosTopHome()
        }
    }
	//传选项卡ADL给App
	function printLog(msg){
		  if(isAndroid){
			 regcallBack.reportChange(msg);
		  }else{
			 window.webkit.messageHandlers.printLog.postMessage(msg);
		  }

	}
	//告知App选项卡的焦点，App跳转more
	function toReportMore(msg){
		  if(isAndroid){
			 regcallBack.toReportMore(msg);
		  }else{
			 window.webkit.messageHandlers.regcallBack.postMessage(msg);
		  }

	}


getEncryptHome();
retEncryptHome();
</script>
</body>

</html>